package com.yh.correct.shiro;

import java.util.ArrayList;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.yh.correct.model.ActiveUser;
import com.yh.correct.model.SysPermission;
import com.yh.correct.model.SysUser;
import com.yh.correct.model.vo.CustomException;
import com.yh.correct.model.vo.Node;
import com.yh.correct.service.ISysUserService;


/**
 * 自定义Realm
 * @author Administrator
 *
 */
public class CustomRealm extends AuthorizingRealm{
	
	private static Logger logger = LogManager.getLogger(CustomRealm.class);
	@Autowired
	private ISysUserService userService;
	
	@Override
	public void setName(String name) {
		// TODO Auto-generated method stub
		super.setName("customRealm");
	}

	/**
	 *认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		// TODO Auto-generated method stub
		String username=(String) token.getPrincipal();
		SysUser user=null;
		try {
			user=userService.findSysUserByUsername(username);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(user==null){
			return null;
		}
		if(user.getStatus()==0){
			throw new LockedAccountException();
		}
		SimpleAuthenticationInfo simpleAuthenticationInfo=new SimpleAuthenticationInfo(user,user.getPassword(),ByteSource.Util.bytes(user.getSalt()),this.getName());
		return simpleAuthenticationInfo;
	}
	
	/**
	 *授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// TODO Auto-generated method stub
		SysUser user=(SysUser) principals.getPrimaryPrincipal();
		List<SysPermission> permissionList=null;
		try {
			permissionList=userService.findPermissionListById(user.getId());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
		for(SysPermission p:permissionList){
			simpleAuthorizationInfo.addStringPermission(p.getCode());
		}
		return simpleAuthorizationInfo;
	}
    		
	
	/**
	 * 清空缓存
	 */
	public void clearCached() {
		PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
		super.clearCache(principals);
	}

}
